/**
 * User: yeqingzhou01
 * Date: 13-9-11
 * Time: 下午6:06
 */
var http = require('http');
var errors = require('../../error/errors');
var urlUtil = require('url');
var util = require('util');
exports.returnData = function(data, message, isSuccess){
    return {
        success: isSuccess,
        message: message ? message : 'OK',
        data: data
    };
}
var checkWSRetObj = function (data, callBack) {
    var isSuccess = function (result) {
        if (result.success) {
            return true;
        }
        return false;
    }
    if (isSuccess(data) && data.data) {
        callBack(data.data);
    } else {
        var msg = '[WS] Web-service problem: ' + data.message || data.msg;
        util.error(msg);
        callBack(
            errors.getErrorInstance(
                errors.errorsName.data,
                msg
            )
        );
    }
}
exports.callREST = function (method, url, params, logicCheck, callBack) {

    var parsedUrl = urlUtil.parse(url, true);

    if(params) {
        if(parsedUrl.query){
            for(var oneKey in params){
                parsedUrl.query[oneKey] = params[oneKey];
            }
        } else {
            parsedUrl.query = params;
        }
        parsedUrl.search=undefined;
    }
    parsedUrl = urlUtil.parse(urlUtil.format(parsedUrl), true);

    var options = {
        host: parsedUrl.port ? parsedUrl.hostname : parsedUrl.host,
        port: parsedUrl.port ? parseInt(parsedUrl.port) : 80,
        path: method != 'POST' ? parsedUrl.path : parsedUrl.pathname,
        method: method ? method : 'GET'
    }

    var req = http.request(options, function(res){
        res.setEncoding('utf8');
        var retData = "";
        res.on('data', function(data){
            retData += data;
        });
        res.on('end', function() {
            retData = JSON.parse(retData);
            if(logicCheck){
                checkWSRetObj(retData, callBack);
            } else {
                callBack(retData);
            }
            util.log('[WS] Request done: ' +
                '[' + method + '] ' + url + ' '
            );
        })
    });

    util.log('[WS] Request started: ' +
        '[' + method + '] ' + url + ' '
    );

    req.on('error', function(e){
        var msg = '[WS] Web-service problem: ' + e.message;
        util.error(msg);
        callBack(
            errors.getErrorInstance(
                errors.errorsName.data,
                msg
            )
        );
    })
    if(method == 'POST') {
        req.write(parsedUrl.search.substr(1));
    }
    req.end();
}
